<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%" max-height="60vh" scroll>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="基本信息" name="1">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="藏品总登记号" prop="generalAccessionNumber">
                <el-input
                  v-model="formData.generalAccessionNumber"
                  placeholder="请输入藏品总登记号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编号类型" prop="numberType">
                <el-select v-model="formData.numberType" placeholder="请选择编号类型">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.COLLECTION_NUM_TYPE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编号" prop="number">
                <el-input v-model="formData.number" placeholder="请输入编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="原名" prop="originalName">
                <el-input v-model="formData.originalName" placeholder="请输入原名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年代" prop="era">
                <!-- chineseHistoricalEra,archaeologicalEra,geologicalEra,era -->
                <!-- eraList -->
                <!-- <el-input v-model="formData.era" placeholder="请输入年代" /> -->
                <el-cascader
                  v-model="formData.eras"
                  :options="eraList"
                  :props="{
                    ...defaultPropsTree,
                    disabled: (data) => data.status === 1
                  }"
                  filterable
                  placeholder="请选择年代"
                  style="width: 100%"
                  @change="onChangeEras"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="具体年代" prop="specificEra">
                <el-input v-model="formData.specificEra" placeholder="请输入具体年代" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文物类别" prop="category">
                <el-select v-model="formData.category" placeholder="请选择文物类别">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.COLLECTION_CATEGORY)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- materialCategory1, materialCategory2, materialCategory3=material -->
              <el-form-item label="质地类别" prop="material">
                <el-cascader
                  v-model="formData.materialCategory3"
                  :options="cataList"
                  :props="{
                    ...defaultPropsTree,
                    disabled: (data) => data.status === 1
                  }"
                  filterable
                  placeholder="请选择质地类别"
                  style="width: 100%"
                  @change="onChangeMaterial"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="件数" prop="numberOfCases">
                <el-input v-model="formData.numberOfCases" placeholder="请输入件数" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位" prop="numberUnit">
                <el-select v-model="formData.numberUnit" placeholder="请选择单位">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.COLLECTION_NUM_UNIT)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实际数量" prop="actualQuantity">
                <el-input v-model="formData.actualQuantity" placeholder="请输入实际数量" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="通长" prop="sizeLength">
                <el-input v-model="formData.sizeLength" placeholder="请输入外形尺寸(cm)-通长" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="通宽" prop="sizeWidth">
                <el-input v-model="formData.sizeWidth" placeholder="请输入外形尺寸(cm)-通宽" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="通高" prop="sizeHeight">
                <el-input v-model="formData.sizeHeight" placeholder="请输入外形尺寸(cm)-通高" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="具体尺寸" prop="specificSize">
                <el-input v-model="formData.specificSize" placeholder="请输入具体尺寸" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="质量范围" prop="weightRange">
                <el-input v-model="formData.weightRange" placeholder="请输入质量-质量范围" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="具体质量" prop="specificWeight">
                <el-input v-model="formData.specificWeight" placeholder="请输入质量-具体质量" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位" prop="weightUnit">
                <el-select v-model="formData.weightUnit" placeholder="请选择质量-单位">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.COLLECTION_QUALITY_UNIT)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="文物级别" prop="relicLevel">
                <el-select v-model="formData.relicLevel" placeholder="请选择文物级别">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.COLLECTION_GRADE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文物来源" prop="relicSource">
                <el-select v-model="formData.relicSource" placeholder="请选择文物来源">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.COLLECTION_SOURCE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="完残程度" prop="completenessDegree">
                <el-select v-model="formData.completenessDegree" placeholder="请选择完残程度">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.COLLECTION_CONDITION_STATUS)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="完残状况" prop="completenessCondition">
                <el-input v-model="formData.completenessCondition" placeholder="请输入完残状况" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="保存状态" prop="preservationState">
                <el-select v-model="formData.preservationState" placeholder="请选择保存状态">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.COLLECTION_PRESERVATION_STATUS)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入藏时间范围" prop="collectionTimeRange">
                <el-input v-model="formData.collectionTimeRange" placeholder="请输入入藏时间范围" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入藏年度" prop="collectionYear">
                <el-input v-model="formData.collectionYear" placeholder="请输入入藏年度" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="藏品登记号" prop="collectionRegistrationNumber">
                <el-input
                  v-model="formData.collectionRegistrationNumber"
                  placeholder="请输入藏品登记号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="版本" prop="version">
                <el-input v-model="formData.version" placeholder="请输入版本" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="存卷" prop="storageVolume">
                <el-input v-model="formData.storageVolume" placeholder="请输入存卷" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="行政区划" prop="administrativeDivision">
                <el-input v-model="formData.administrativeDivision" placeholder="请输入行政区划" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位编码" prop="unitCode">
                <el-input v-model="formData.unitCode" placeholder="请输入单位编码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位名称" prop="unitName">
                <el-input v-model="formData.unitName" placeholder="请输入单位名称" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="扩展信息" name="2" v-if="['10', '13'].includes(formData.category)">
          <!--      书画类藏品特有字段-->
          <el-row :gutter="20" v-if="formData.category === '10'">
            <el-col :span="8">
              <el-form-item label="画心尺寸-长" prop="paintingLength">
                <el-input v-model="formData.paintingLength" placeholder="请输入画心尺寸-长">
                  <template #append>cm</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="宽" prop="paintingWidth">
                <el-input v-model="formData.paintingWidth" placeholder="请输入画心尺寸-宽">
                  <template #append>cm</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="高" prop="paintingHeight">
                <el-input v-model="formData.paintingHeight" placeholder="请输入画心尺寸-高">
                  <template #append>cm</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="装裱尺寸-长" prop="mountingLength">
                <el-input v-model="formData.mountingLength" placeholder="请输入装裱尺寸-长">
                  <template #append>cm</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="宽" prop="mountingWidth">
                <el-input v-model="formData.mountingWidth" placeholder="请输入装裱尺寸-宽">
                  <template #append>cm</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="高" prop="mountingHeight">
                <el-input v-model="formData.mountingHeight" placeholder="请输入装裱尺寸-高">
                  <template #append>cm</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="内容题材" prop="subjectMatter">
                <el-input v-model="formData.subjectMatter" placeholder="请输入内容题材" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="技法风格" prop="techniqueStyle">
                <el-input v-model="formData.techniqueStyle" placeholder="请输入技法风格" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="款识信息" prop="inscriptionInfo">
                <el-input v-model="formData.inscriptionInfo" placeholder="请输入款识信息" />
              </el-form-item>
            </el-col>
          </el-row>

          <!--      印章类藏品特有字段-->
          <el-row :gutter="20" v-else>
            <el-col :span="12">
              <el-form-item label="形状" prop="shape">
                <el-input v-model="formData.shape" placeholder="请输入形状" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="钮式" prop="knobStyle">
                <el-input v-model="formData.knobStyle" placeholder="请输入钮式" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文字类型" prop="textType">
                <el-select v-model="formData.textType" placeholder="请选择文字类型">
                  <el-option label="请选择字典生成" value="" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="边框特征" prop="borderFeature">
                <el-input v-model="formData.borderFeature" placeholder="请输入边框特征" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="印面尺寸" prop="sealSize">
                <el-input v-model="formData.sealSize" placeholder="请输入印面尺寸" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="印文排列" prop="textArrangement">
                <el-input v-model="formData.textArrangement" placeholder="请输入印文排列" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="印文内容" prop="sealContent">
                <Editor v-model="formData.sealContent" height="150px" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="藏品附件" name="3">
          <el-form-item label="附件信息" prop="attachments">
            <UploadFile v-model="formData.attachments" />
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane name="4" :disabled="!formData.id">
          <template #label>
            <el-tooltip
              effect="dark"
              content="请先保存基本信息"
              placement="top-start"
              :disabled="!!formData.id"
            >
              <span>二维采集信息</span>
            </el-tooltip>
          </template>
          <collectionimageacquisition :data="formData" />
        </el-tab-pane>
        <el-tab-pane name="5" :disabled="!formData.id">
          <template #label>
            <el-tooltip
              effect="dark"
              content="请先保存基本信息"
              placement="top-start"
              :disabled="!!formData.id"
            >
              <span>三维采集信息</span>
            </el-tooltip>
          </template>
          <collection3dacquisition :data="formData" />
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">保 存</el-button>
      <el-button @click="closeForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { defaultPropsTree, handleTree } from '@/utils/tree'
import { CollectionManagementApi, CollectionManagementVO } from '@/api/museum/collectionmanagement'
import { getDictDataByParentId } from '@/api/system/dict/dict.data'
import collectionimageacquisition from '../collectionimageacquisition/index.vue'
import collection3dacquisition from '../collection3dacquisition/index.vue'

/** 藏品管理 表单 */
defineOptions({ name: 'CollectionManagementForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const activeTab = ref('1') // 活动的标签页
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<any>({})
const formRules = reactive({
  generalAccessionNumber: [{ required: true, message: '总登记号不能为空', trigger: 'blur' }],
  category: [{ required: true, message: '类别不能为空', trigger: 'change' }],
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  originalName: [{ required: true, message: '原名不能为空', trigger: 'blur' }],
  coverImage: [{ required: true, message: '封面图片路径不能为空', trigger: 'blur' }],
  materialType: [{ required: true, message: '质地类别不能为空', trigger: 'change' }],
  actureQuantity: [{ required: true, message: '实际数量不能为空', trigger: 'blur' }],
  quality: [{ required: true, message: '质量不能为空', trigger: 'blur' }],
  quantity: [{ required: true, message: '件数(套)不能为空', trigger: 'blur' }],
  grade: [{ required: true, message: '级别不能为空', trigger: 'change' }],
  source: [{ required: true, message: '来源不能为空', trigger: 'change' }],
  conditionStatus: [{ required: true, message: '完残状况不能为空', trigger: 'change' }],
  preservationStatus: [{ required: true, message: '保存状态不能为空', trigger: 'change' }],
  entryDate: [{ required: true, message: '入馆日期不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  getDictData()
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CollectionManagementApi.getCollectionManagement(id)
      const materialCategory3: number[] = []
      if (formData.value.materialCategory1)
        materialCategory3.push(+formData.value.materialCategory1)
      if (formData.value.materialCategory2)
        materialCategory3.push(+formData.value.materialCategory2)
      if (formData.value.material) materialCategory3.push(+formData.value.material)
      materialCategory3.filter((val) => val || val === 0)
      formData.value.materialCategory3 = materialCategory3

      const eras: number[] = []
      if (formData.value.chineseHistoricalEra) eras.push(+formData.value.chineseHistoricalEra)
      if (formData.value.archaeologicalEra) eras.push(+formData.value.archaeologicalEra)
      if (formData.value.geologicalEra) eras.push(+formData.value.geologicalEra)
      if (formData.value.era) eras.push(+formData.value.era)
      formData.value.eras = eras
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const cataList = ref<any[]>([])
const eraList = ref<any[]>([])
const getDictData = () => {
  getDictDataByParentId({ parentId: 1 }).then((res) => {
    console.log('getDictDataByParentId res', res)
    cataList.value = handleTree(res)
  })
  getDictDataByParentId({ parentId: 1901 }).then((res) => {
    console.log('getDictDataByParentId res', res)
    eraList.value = handleTree(res)
  })
}
// materialCategory1, materialCategory2, materialCategory3=material
const onChangeMaterial = (values) => {
  console.log('onChangeMaterial values', values)
  formData.value.materialCategory1 = values[0]
  formData.value.materialCategory2 = values[1]
  formData.value.material = values[2]
}
// chineseHistoricalEra,archaeologicalEra,geologicalEra,era
const onChangeEras = (values) => {
  console.log('onChangeEras values', values)
  formData.value.chineseHistoricalEra = values[0]
  formData.value.archaeologicalEra = values[1]
  formData.value.geologicalEra = values[2]
  formData.value.era = values[3]
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CollectionManagementVO
    if (!data.id) {
      const res = await CollectionManagementApi.createCollectionManagement(data)
      console.log('createCollectionManagement res', res)
      message.success(t('common.actionSuccess'))
      formData.value.id = res.id
    } else {
      await CollectionManagementApi.updateCollectionManagement(data)
      message.success(t('common.actionSuccess'))
    }
  } finally {
    formLoading.value = false
  }
}

const closeForm = () => {
  dialogVisible.value = false
  // 发送操作成功的事件
  emit('success')
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {}
  formRef.value?.resetFields()
}
</script>
